import React from 'react';
import PropTypes from 'prop-types';

import Dialog from '@kuiper-components/dialog';

import s from './BindWechat.module.css';
import DialogContent from './DialogContent';
import fetch from 'API/fetch';
import notification from '@kuiper-components/notification';
import Message from '@knownsec/react-component/dist/Message';

export default function BindWechat({ children, refetch, uid, ...props }) {
	const [dialogVisible, setDialogVisible] = React.useState(false);

	const handleClose = () => {
		setDialogVisible(false);
		refetch();
	};

	const checkWxBind = () => {
		fetch(`/api/v2/alerts/check_wx_bind`, {
			method: 'GET',
		}).then(res => {
			if (res.msg === 'success') {
				setDialogVisible(false);
				Message.show({
					type: 'success',
					message: '微信绑定成功！',
					onclose() {
						refetch();
					},
				});
			}
		});
	};

	let timer = null;
	React.useEffect(
		function () {
			if (dialogVisible) {
				timer = setInterval(function () {
					checkWxBind();
				}, 2000);
			} else {
				clearInterval(timer);
			}
			return () => {
				clearInterval(timer);
			};
		},
		[dialogVisible]
	);

	return (
		<>
			{React.cloneElement(children, {
				...children.props,
				onClick(e) {
					if (children.props.onClick) children.props.onClick(e);
					setDialogVisible(true);
				},
			})}
			<Dialog
				visible={dialogVisible}
				destroyOnClose={true}
				title={'绑定微信'}
				wrapClassName={s.dialog}
				{...props}
				onClose={handleClose}
			>
				<DialogContent uid={uid} onClose={handleClose} />
			</Dialog>
		</>
	);
}

BindWechat.propTypes = {
	children: PropTypes.element.isRequired,
	uid: PropTypes.string,
	refetch: PropTypes.func,
};

BindWechat.defaultProps = {};
